<?php
require_once(WEBSITE_ROOT.'/common/init.php');
class user {
    
    function __construct() {
        
    }

    static public function is_logged(){
        $user_id = SESSION_value('user_id',0);
        return $user_id;
    }

    static public function Get_group_id($user_id){
       
       global $dbdefault;
       $query=sprintf("SELECT group_id from users where user_id=",quote_smart($user_id));
       $result=mysql_query($query,$dbdefault);
       $group_id=mysql_result($result,0,'group_id');
       return $group_id;
       }
    static public function login($data)
    {
        global $dbdefault;
       //echo 'loggin in...';
       $user_name=$data['user_name'];
       $user_password=$data['user_password'];
       $remember_me=$data['remember_me'];
       $user_password=md5($user_password);
       $query=sprintf(" SELECT user_id,user_name,group_id,user_password
                FROM users WHERE user_name=%s and status='1'", quote_smart($user_name));

       $result = mysql_query($query,$dbdefault);       
       if (!$result) return array('success'=>FALSE,'error'=>  mysql_error());

       $ok = mysql_num_rows($result);
       if ($ok){
          $arr =  mysql_fetch_assoc($result);
          if ($user_password!=$arr['user_password']) return array('success'=>FALSE,'error'=>'Incorrect password!');
          
          $query_layout=sprintf("select is_prolayout from groups where group_id=%d",qs($arr['group_id']));
          $res_layout=mysql_query($query_layout,$dbdefault) or die(mysql_error()."<br />".$qry);
          $prolayout=mysql_result($res_layout,0,'is_prolayout');
          // SET SESSION
          $_SESSION['user_id']=$arr['user_id'];
          $_SESSION['user_name']=$arr['user_name'];
          $_SESSION['prolayout']=$prolayout;
          if (!empty($remember_me)){
             echo "remember_me!!!";
             $cookie_pass=str_makerand(5); $cookie_pass=md5($cookie_pass);
             $query=sprintf("UPDATE users SET cookie_password=%s WHERE user_id=%d",
                           quote_smart($cookie_pass),quote_smart($arr['user_id']));
             mysql_query($query,$dbdefault);
             $cookie_time=time()+3600*24*7; // Remember me for 7 days
             setcookie("cookie_password", $cookie_pass,$cookie_time,'/',COOKIE_DOMAIN);
             setcookie("cookie_username", $arr['user_name'],$cookie_time,'/',COOKIE_DOMAIN);
          }
          return array('success'=>TRUE);
       }else{
          return array('success'=>FALSE,'error'=>'Username not found!');
       }
    }

    static public function logout(){
       $_SESSION['user_id']='0';
       $_SESSION['user_name']='';
       $_SESSION['prolayout']='';
       $cookie_time=time()-3600*24*30; // Remove cookie
       $ok=setcookie("cookie_password",false,$cookie_time,'/',COOKIE_DOMAIN);
       $ok=setcookie("cookie_username",false,$cookie_time,'/',COOKIE_DOMAIN);
       return true;        
    }
    
    static public function update($user_id,$data){
        
        $form_error=array();
        $updates = array();
        $updates[]=sprintf('user_realname=%s',  quote_smart($data['user_realname']));
        $updates[]=sprintf('group_id=%d',  $data['group_id']);
        $r = User::validate_email($data['user_email'],'update');
        if (!$r['success']) {
            $form_error['user_email']=$r['error'];    
        }else{
            $updates[]=sprintf('user_email=%s',  quote_smart($data['user_email']));
            $updates[]=sprintf('idcustomer=%d ',  quote_smart($data['idcustomer']) );
            $updates[]=sprintf('status=%d ',  quote_smart($data['status']) );
        }
        if (!empty($data['user_password'])){
        $r = User::validate_password($data['user_password'],$data['user_password1']);
            if (!$r['success']) {
                $form_error['user_password']=$r['error'];    
            }else{
                $updates[]=sprintf('user_password=%s ',  quote_smart(md5($data['user_password'])) );
                
            }
        }
        
        if (!count($form_error)){
            $where=  sprintf('user_id=%d', $data['user_id']);
            $r = mysql_update('users',$updates,$where);
            if ($r['success']){
               return array('success'=>TRUE);
            }else{
               return array('success'=>FALSE,'error'=>$r['error'],'form_error'=>null);
            }
        }else{
            return array('success'=>FALSE,'form_error'=>$form_error);
        }
    }

    static public function passwd($user_id,$data){
        //Check password
        global $dbdefault;
        $query = sprintf("SELECT count(*) as total FROM users WHERE user_id=%d AND user_password=%s",$user_id,quote_smart(md5($data['user_password'])));
        $result = mysql_query($query,$dbdefault) or die(__CLASS__."(".__LINE__."):".mysql_error());
        $match = mysql_result($result,0, 'total');
        if (!$match){
            return array('success'=>FALSE,'error'=>'Mật khẩu cũ không đúng');    
        }
        $updates = array();
        //Validate passowrd
        $r = User::validate_password($data['new_user_password'],$data['confirm_user_password']);
        if (!$r['success']) {
            return array('success'=>FALSE,'error'=>$r['error']);    
        }else{
            $updates[]=sprintf('user_password=%s',  quote_smart(md5($data['new_user_password'])) );
            $where=  sprintf('user_id=%d', $user_id);
            $r = mysql_update('users',$updates,$where);
            if ($r['success']){
               return array('success'=>TRUE);
            }else{
               return array('success'=>FALSE,'error'=>$r['error']);
            }
        }
    }  
    static public function delete($user_id){
        global $dbdefault;
        $query="DELETE from users WHERE user_id=$user_id";
        $query_check="Select user_name from users WHERE user_id=$user_id";
        $result_check=  @mysql_query($query_check,$dbdefault);
        $r=mysql_fetch_assoc ($result_check);
        $user_name=$r['user_name'];
        if($user_name=="root"){
            return array('success'=>FALSE,'error'=> "Can not delete root user");
        }
        else {
            $result=@mysql_query($query,$dbdefault);
            if (!$result){
                echo mysql_error();
                return array('success'=>FALSE,'error'=> mysql_error());
            }else{
                return array('success'=>TRUE,'content'=>" is deleted");
            }
        }
    }

    /**/
    static public function get_user_data($user_id){
        global $dbdefault;
        $query = "SELECT * FROM users WHERE user_id=$user_id";
        $result= @mysql_query($query,$dbdefault);
        if (!$result){
            return array('success'=>FALSE,'error'=> mysql_error());
        }else{
            $nr = mysql_num_rows($result);
            if ($nr){
                return array('success'=>TRUE,'data'=>  mysql_fetch_assoc($result));
            }else{
                return array('success'=>FALSE,'error'=>"User doesn't exist");
            }
        }
    }
    /*Create user*/
    static public function create($data){
        global $dbdefault;
        $r = User::validate($data);
        if ($r['success']) {
            $user_password = md5($data['user_password']);
            $query=sprintf(" INSERT INTO users
                (user_name,user_email,user_password,user_realname,user_created,group_id, idcustomer)
                VALUE(%s,%s,%s,%s,sysdate(),%d, %d) ",
                quote_smart($data['user_name']),quote_smart($data['user_email']),quote_smart($user_password),quote_smart($data['user_realname']),$data['group_id'],$data['idcustomer']);
            //echo $query;
            $result= @mysql_query($query,$dbdefault);
            if (!$result){
                return array('success'=>FALSE,'error'=> mysql_error(),'form_error'=>null);
            }else{
                return array('success'=>TRUE,'user_id'=>mysql_insert_id());
            }
        }else{
            //print_r($r);
            return array('success'=>FALSE,'error'=>$r['error'],'form_error'=>$r['form_error']);
        }
    }
    
    /*Validate user information*/
    static public function validate($data,$mode='insert'){
        $error='';
        $form_error=array();
        $r = User::validate_username($data['user_name']);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_name']=$r['error'];    
        }
        $r = User::validate_email($data['user_email'],$mode);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_email']=$r['error'];    
        }
        $r = User::validate_password($data['user_password'],$data['user_password1']);
        if (!$r['success']) {
            $error .= $r['error'].'<br/>';
            $form_error['user_password']=$r['error'];    
        }
        if (empty($error)){
            return array('success'=>TRUE);
        }else{
            return array('success'=>FALSE,'error'=>'','form_error'=>$form_error);
        }
    }

    static public function validate_username($user_name)
    {
       global $dbdefault;
        $user_name=trim($user_name);
       // Check only legal characters are used
       if (!preg_match('/^[A-Za-z0-9_]{2,30}$/',$user_name)){
          return array('success'=>FALSE,'error'=>'Invalid username!');
       }
       // Check there's no duplicate user_name
       $query=sprintf("SELECT count(*) as existed FROM users WHERE user_name=%s",quote_smart($user_name));
       $result=mysql_query($query,$dbdefault) or die(__CLASS__.'->'.__METHOD__.':'.mysql_error());
       $existed=mysql_result($result,0,'existed');
       if ($existed){
          return array('success'=>FALSE,'error'=>'Username existed!');
       }
       return array('success'=>TRUE);
    }

    static public function validate_email($email,$mode='insert')
    {
       global $dbdefault;
        $email=trim($email);
       // Check only legal characters are used
       if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)){
          return array('success'=>FALSE,'error'=>'Invalid email!');
       }
       if ('update'==$mode) return array('success'=>TRUE);
       // Check there's no duplicate user_name
       $query=sprintf("SELECT count(*) as existed FROM users WHERE user_email=%s",quote_smart($email));
       $result=mysql_query($query,$dbdefault) or die(mysql_error());
       $existed=mysql_result($result,0,'existed');
       if ($existed){
          return array('success'=>FALSE,'error'=>'Email existed!');
       }
       return array('success'=>TRUE);
    }

    static function validate_password($pass,$pass1)
    {
        if (strlen($pass)<3){
            return array('success'=>FALSE,'error'=>'Password must be at least 3 characters!');
        }
        if ($pass !== $pass1){
            return array('success'=>FALSE,'error'=>'Passwords do not match!');
        }
        return array('success'=>TRUE);       
    }
    

}